<template>
  <div class="appcontainer">
    <el-row style="width: 100%; height: 100%">
      <el-col :span="5" style="height: 100%" >
        <div class="calendar_body_left_bottom">
          <div class="calendar_body_left_bottom_title">拖拽列表</div>
          <div class="date-box" id="list-group-item">
            <div
              class="flex-b box list-group-item"
              :class="item.status"
              v-for="item in list"
              :key="item.name"
            >
              <div>{{ item.name }}</div>
            </div>
          </div>
          <!-- <div style="margin-top: 20px;">
            <el-checkbox v-model="checked">移动后删除</el-checkbox>
          </div> -->
          <div class="calendar_header">
            <el-input v-model="addval" placeholder="请输入" style="width: 69%"></el-input>
            <el-button type="primary" @click="addList()">+ 新增</el-button>
          </div>
        </div>
      </el-col>
      <el-col
        :span="19"
        style="
          height: 100%;
          padding-top: 20px;
          padding-left: 20px;
          padding-right: 3%;
          box-sizing: border-box;
        "
      >
        <FullCalendar ref="fullCalendar" :options="calendarOptions" />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listCalendar, getCalendar, delCalendar, addCalendar, updateCalendar } from "@/api/system/calendar";
import moment from "moment";
import FullCalendar from "@fullcalendar/vue";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin, { Draggable } from "@fullcalendar/interaction";
import listPlugin from "@fullcalendar/list";
import locale from "@fullcalendar/core/locales/zh-cn";
import { INITIAL_EVENTS, createEventId } from "@/utils/event-utils";
export default {
  name: "Calendar",
  components: {
    FullCalendar, // make the <FullCalendar> tag available
  },
  data() {
    return {
      n: 4,
      addval: "",
      dialogFormVisible: false,
      formLabelWidth: "120px",
      testData: [
        {
          id: 1,
          title: "任务1未开始",
          start: "2023-04-06 10:30:00",
          end: "2023-04-07 10:30:00",
          // color: '#ffcc99',
          status: "unstart",
          editable: false, //允许拖动缩放，不写默认就是false
          overlap: true, //允许时间重叠，即可以与其他事件并存，不写默认就是false
        },
        {
          id: 2,
          title: "任务2进行中",
          start: "2023-04-06 10:30:00",
          end: "2023-04-08 10:30:00",
          // color: '#5580ee',
          status: "doing",
          editable: false, //允许拖动缩放
          overlap: true, //允许时间重叠，即可以与其他事件并存，不写默认就是false
        },
        {
          id: 3,
          title: "任务3已完成",
          start: "2023-04-09 10:30:00",
          end: "2023-04-09 18:30:00",
          // color: '#87d068',
          status: "success",
          editable: false, //允许拖动缩放
          overlap: true, //允许时间重叠，即可以与其他事件并存，不写默认就是false
        },
        {
          id: 4,
          title: "任务4已延时",
          start: "2023-04-18 10:30:00",
          end: "2023-04-18 10:30:00",
          // color: '#ff99b3',
          status: "delay",
          editable: false, //允许拖动缩放
          overlap: true, //允许时间重叠，即可以与其他事件并存，不写默认就是false
        },
        {
          id: 5,
          title: "任务5错误",
          start: "2023-04-18 10:30:00",
          end: "2023-04-18 10:30:00",
          // color: '#ff99b3',
          status: "error",
          editable: false, //允许拖动缩放
          overlap: true, //允许时间重叠，即可以与其他事件并存，不写默认就是false
        },
        {
          id: 6,
          title: "任务6信息",
          start: "2023-04-18 10:30:00",
          end: "2023-04-18 10:30:00",
          // color: '#ff99b3',
          status: "info",
          editable: false, //允许拖动缩放
          overlap: true, //允许时间重叠，即可以与其他事件并存，不写默认就是false
        },
      ],
      // 可拖动列表数据
      list: [
        // { name: '删除假日', value: '0', color: 'blue'  }
        { name: "休息日", value: "1", status: "unstart" },
        //   { name: '培训', value: '5', status: 'doing' },
        //   { name: '出差', value: '5', status: 'error' },
        // { name: '春节放假', value: '7', status: 'success' },
        // { name: '中秋节放假', value: '3', status: 'delay' },
        // { name: '国庆节放假', value: '7', status: 'info' },
      ],
      calendarOptions: {
        plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin],
        initialView: "dayGridMonth",
        locale: "zh-cn", //? 配置中文
        firstDay: 1, // 把每周设置为从周一开始
        initialDate: moment().format("YYYY-MM-DD HH:mm:ss"), // 自定义设置背景颜色时一定要初始化日期时间
        aspectRatio: 2.6, // 设置日历单元格宽度与高度的比例。
        buttonText: {
          /* 设置按钮文字 */ today: "今天",
          month: "月",
          week: "周",
          day: "日",
          list: "周列表",
        },
        headerToolbar: {
          //日历头部
          left: "prev,next today",
          center: "title",
          // dayGridMonth,timeGridWeek,timeGridDay listWeek
          right: "",
        },
        selectable: true, //可编辑
        // dayMaxEvents: true,
        // slotMinutes: 15,
        editable: false, // 日历上是否可拖拽
        droppable: true,
        dropAccept: ".list-group-item",
        drop: this.drop,
        height: 650,
        eventDisplay: "block",
        validRange: this.validRange, //设置可显示的总日期范围
        events: [], //背景色 (添加相同时间的背景色时颜色会重叠)
        datesSet: this.datesSet, //日期渲染；修改日期范围后触发
        eventClick: this.handleEventClick, //点击日程触发
        dateClick: this.handleDateClick, //点击日期触发
        eventDrop: this.calendarEventDropOrResize, //拖动事件触发
        eventResize: this.calendarEventDropOrResize, //缩放事件触发
        displayEventTime: false, //不显示具体时间
      },
      validRange: {
        start: "2023-01-01 ",
        end: moment().add(6, "months").format("YYYY-MM-DD HH:mm:ss"),
      },
      new_startDate: "",
      new_endDate: "",
      checked: false,
    };
  },
  created() {},
  mounted() {
    // 初始化日历 调用获取视图活动数据方法
    this.datesSet();

    // 拖拽
    var containerEl = document.getElementById("list-group-item");
    // 初始化外部事件
    new Draggable(containerEl, {
      itemSelector: ".list-group-item",
    });
  },
  methods: {
    handleWeekendsToggle() {
      this.calendarOptions.weekends = !this.calendarOptions.weekends; // update a property
    },

    handleDateSelect(selectInfo) {
      let title = prompt("Please enter a new title for your event");
      let calendarApi = selectInfo.view.calendar;

      calendarApi.unselect(); // clear date selection

      if (title) {
        calendarApi.addEvent({
          id: createEventId(),
          title,
          start: selectInfo.startStr,
          end: selectInfo.endStr,
          allDay: selectInfo.allDay,
        });
      }
    },

    handleEventClick(clickInfo) {
      console.log(clickInfo, 888888888888);
      let id = clickInfo.event.id;
      this.$confirm("是否删除此日程", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delCalendar(id).then((res) => {
            if (res.code == 200) {
              clickInfo.event.remove();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this$nextTick(() => {
                this.datesSet();
              });
            }
          });
        })
        .catch(() => {});
    },

    handleEvents(events) {
      this.currentEvents = events;
    },
    addList() {
      if (this.addval == "" || this.addval == null) {
        this.$message.warning("内容不能为空");
        reutrn;
      }
      let yy = new Date().getFullYear();
      let mm =
        new Date().getMonth() + 1 < 10
          ? "0" + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      let dd =
        new Date().getDate() < 10 ? "0" + new Date().getDate() : new Date().getDate();
      let hh =
        new Date().getHours() < 10 ? "0" + new Date().getHours() : new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      var nowTime = yy + "-" + mm + "-" + dd + " " + "00:00:00";
      var nowTime1 = yy + "-" + mm + "-" + dd + " " + "23:59:59";
      var status = ["unstart", "doing", "success", "delay", "error", "info"];
      // 获取数组长度
      var numColors = status.length;
      // 生成一个随机索引
      var randomIndex = Math.floor(Math.random() * numColors);
      var obj = {
        name: this.addval,
        value: "1",
        status: status[randomIndex],
      };
      this.list.push(obj);
      sessionStorage.setItem("list", JSON.stringify(this.list));
      this.datesSet();
    },
    datesSet(info) {
      //注意：该方法在页面初始化时就会触发一次
      // console.log(info)
      // this.search()  //请求本页数据
      if (this.list.length == 0) {
        this.list = JSON.parse(sessionStorage.getItem("list"));
      }
      //虚拟数据
      listCalendar().then((res) => {
        this.testData = [];
        if (res.length != 0) {
          res.map((item) => {
            var json = {
              id: item.id,
              status: item.color || "info",
              start: item.startTime + " " + "00:00:00",
              end: item.endTime + " " + "00:00:00",
              title: item.title,
              editable: false, //允许拖动缩放
              overlap: true, //允许时间重叠，即可以与其他事件并存，不写默认就是false
            };
            this.testData.push(json);
          });
        }
        // this.testData = res
        if (this.testData.length != 0) {
          this.testData.forEach((item, index) => {
            console.log("item", item);
            if (item.status == "unstart") {
              this.$set(item, "color", "#4187ac");
            } else if (item.status == "doing") {
              this.$set(item, "color", "#62c0dd");
            } else if (item.status == "success") {
              this.$set(item, "color", "#5db860");
            } else if (item.status == "delay") {
              this.$set(item, "color", "#edad54");
            } else if (item.status == "error") {
              this.$set(item, "color", "#dc6765");
            } else {
              this.$set(item, "color", "#FF6600");
            }
          });
          console.log(this.testData, 9999999999999999);
          this.calendarOptions.events = this.testData;
          this.list.forEach((item, index) => {
            if (item.status == "unstart") {
              this.$set(item, "color", "#4187ac");
            } else if (item.status == "doing") {
              this.$set(item, "color", "#62c0dd");
            } else if (item.status == "success") {
              this.$set(item, "color", "#5db860");
            } else if (item.status == "delay") {
              this.$set(item, "color", "#edad54");
            } else if (item.status == "error") {
              this.$set(item, "color", "#dc6765");
            } else {
              this.$set(item, "color", "#FF6600");
            }
          });
          console.log(this.list, "----------------");
          sessionStorage.setItem("list", JSON.stringify(this.list));
        }
      });
    },
    // 转换时间格式
    parseTime(date) {
      const yy = date.getFullYear();
      const MM =
        date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      const dd = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      const HH = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      const mm = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      const ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      const newDate = yy + "-" + MM + "-" + dd + " " + HH + ":" + mm + ":" + ss;
      return newDate;
    },
    // 拖拽事件
    calendarEventDropOrResize(info) {
      // console.log(info) //获取拖拽目标信息
      // 获取拖拽后的时间
      this.new_startDate = this.parseTime(info.event._instance.range.start);
      this.new_endDate = this.parseTime(info.event._instance.range.end);
    },
    drop(date, allDay) {
      if (date.draggedEl.classList.length != 0) {
        var className1 = date.draggedEl.classList[3];
        console.log(className1, 66666666666);
      } else {
        var className1 = date.draggedEl.className.slice(27);
        console.log(className1, 66666666666);
      }
      if (this.checked == true) {
        date.draggedEl.remove();
        sessionStorage.setItem("list", JSON.stringify(this.list));
      }
      this.n++;
      const obj = {
        id: Number(this.n),
        title: String(date.draggedEl.firstChild.innerHTML),
        start: Date.parse(moment(date.dateStr).format()), // 开始时间
        end: Date.parse(
          moment(date.dateStr).add(date.draggedEl.lastChild.innerHTML, "days").format()
        ), // 结束时间
        // color: '#ff99b3',
        status: className1,
        editable: false, //允许拖动缩放
        overlap: true, //允许时间重叠，即可以与其他事件并存，不写默认就是false
      };
      console.log(obj, 55555555555555);
      this.testData.push(obj);
      var date = new Date(obj.start); // 时间戳转换成Date对象
      var year = date.getFullYear(); // 获取年份
      var month = ("0" + (date.getMonth() + 1)).slice(-2); // 获取月份，转为两位数
      var day = ("0" + date.getDate()).slice(-2); // 获取日，转为两位数
      // 根据需要格式化时间，这里是 YYYY-MM-DD HH:mm:ss
      let starttime = `${year}-${month}-${day}`;
      var date = new Date(obj.end); // 时间戳转换成Date对象
      var year = date.getFullYear(); // 获取年份
      var month = ("0" + (date.getMonth() + 1)).slice(-2); // 获取月份，转为两位数
      var day = ("0" + date.getDate()).slice(-2); // 获取日，转为两位数
      // 根据需要格式化时间，这里是 YYYY-MM-DD HH:mm:ss
      let endtime = `${year}-${month}-${day}`;
      console.log(starttime, endtime, obj, 88888888888888);
      let query = {
        title: obj.title,
        startTime: starttime,
        endTime: endtime,
        color: obj.status,
        userName: sessionStorage.getItem("nick"),
      };
      addCalendar(query).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.datesSet();
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .fc .fc-button-group > .fc-button {
  background-color: #47a2de;
  border-color: #47a2de;
}

::v-deep .fc .fc-button-primary {
  background-color: #47a2de;
  border-color: #47a2de;
}

::v-deep .fc .fc-button-primary:active {
  background-color: #47a2de;
  border-color: #47a2de;
}

.el-button {
  width: 100px;
}

.calendar_header {
  display: flex;
  margin: 30px 0;

  .el-input {
    width: 200px;
    margin-right: 16px;
  }
}

.el-button {
  margin-left: 0 !important;
  color: #fff;
  margin-bottom: 4px;
}

.unstart_btn {
  background-color: #ffcc99;
}

.doing_btn {
  background-color: #5580ee;
}

.success_btn {
  background-color: #87d068;
}

.delay_btn {
  background-color: #ff0033;
}

.el-dialog {
  width: 30%;
}

.el-date-editor.el-range-editor.el-input__inner.el-date-editor--datetimerange {
  width: 100%;
}

.el-select {
  width: 100%;
}

.calendar_body_left_top {
  .calendar_body_left_top_title {
    margin-bottom: 15px;
    font-size: 18px;
    font-weight: bolder;
  }
}

.calendar_body_left_bottom {
  padding: 15px 25px;
  box-sizing: border-box;
  margin-top: 20px;
  background-color: #eeeeee;

  .calendar_body_left_bottom_title {
    font-size: 18px;
    font-weight: bolder;
  }

  .circle {
    background-color: #3788d8;
    border-radius: 10px;
    color: #fff;
    display: inline-block;
    font-size: 12px;
    height: 18px;
    line-height: 18px;
    padding: 0 6px;
    text-align: center;
    white-space: nowrap;
    border: 1px solid #fff;
  }

  .unstart {
    background-color: #4187ac;
    border: 1px solid #4187ac;
  }

  .doing {
    background-color: #62c0dd;
    border: 1px solid #62c0dd;
  }

  .success {
    background-color: #5db860;
    border: 1px solid #5db860;
  }

  .delay {
    background-color: #edad54;
    border: 1px solid #edad54;
  }

  .error {
    background-color: #dc6765;
    border: 1px solid #dc6765;
  }

  .info {
    background-color: #ff6600;
    border: 1px solid #ff6600;
  }

  .date-box {
    border-radius: 5px;
  }

  .box {
    margin-top: 15px;
    padding: 5px 20px;
    border-radius: 5px;
    display: flex;
    justify-content: space-between;
    cursor: pointer;
    color: #fff;
  }
}
</style>
